package com.zxq.demo.core.utils;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zxq.demo.core.model.ZxqJobInfo;
import com.zxq.demo.core.properties.JobDataSourceProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.sql.*;
import java.util.Map;

/**
 * @author zw
 * @description
 * @email 2408003640@qq.com
 * @date 2025/6/15 13:14
 */
@Slf4j
@Component
public class JobDataUtils {
    private static JobDataSourceProperties jobDataSourceProperties;
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("MySQL JDBC Driver not found", e);
        }
    }

    public JobDataUtils(JobDataSourceProperties jobDataSourceProperties) {
        JobDataUtils.jobDataSourceProperties = jobDataSourceProperties;
    }

    public static ZxqJobInfo getJobDataById(Long id) {
        JSONObject result = executeSql("SELECT * FROM zxq_job_info WHERE id = " + id);
        return JSONUtil.toBean(result, ZxqJobInfo.class);
    }
    private static Connection getConnection() throws SQLException {
        // 假设使用的是MySQL数据库，需替换为实际的数据库URL、用户名和密码
        String url = jobDataSourceProperties.getUrl();
        String username = jobDataSourceProperties.getUsername();
        String password = jobDataSourceProperties.getPassword();
        // 创建数据库连接
        return DriverManager.getConnection(url, username, password);
    }
    private static JSONObject executeSql(String sql) {
        Connection connection = null;
        JSONObject result = new JSONObject();
        try {
            connection = getConnection();
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery(sql);
            ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
            if (resultSet.next()) {
                for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {
                    String columnLabel = resultSetMetaData.getColumnLabel(i);
                    String columnName = resultSetMetaData.getColumnName(i);
                    Object columnValue = resultSet.getObject(columnLabel);
                    result.set(columnName, columnValue);
                }
            }
            // 关闭资源（根据需求调整）
            resultSet.close();
            statement.close();
        } catch (Exception e) {
            log.error("sql查询失败");
            throw new RuntimeException(e);
        } finally {
            if (connection != null) {
                try {
                    connection.close(); // 关闭连接
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}
